renderStudentList()//渲染学生列表
initcitySelect()//初始化省市区

const tbody = document.querySelector('tbody');
const openModal = document.querySelector('#openModal');//点击显示表单
const modalBootstrap = new bootstrap.Modal('.modal')//模态框显示隐藏
const province = document.querySelector('[name="province"]');//省
const city = document.querySelector('[name="city"]');//市
const area = document.querySelector('[name="area"]');//区
const formAdd = document.querySelector('#form');//表单
//渲染学生列表
async function renderStudentList() {
    const result = await axios({
        url: '/students',
    })
    const html = result.data.reduce((a, b) => a + `<tr>
    <td>${b.name}</td>
    <td>${b.age}</td>
    <td>${b.gender === 1 ? '女' : '男'}</td>
    <td>${b.group}</td>
    <td>${b.hope_salary}</td>
    <td>${b.salary}</td>
    <td>${b.province + b.city + b.area}</td>
    <td>
      <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id=${b.id}></i></a>
      <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id=${b.id}></i></a>
    </td>
  </tr>`, '')
    tbody.innerHTML = html
    document.querySelector('.total').innerText = result.data.length
}

// 点击显示模态框
openModal.addEventListener('click', function (e) {
    document.querySelector('.modal-title').innerText = '添加学员'
    modalBootstrap.show()
    formAdd.reset()//无法重置下拉列表

})

//手动重置下拉列表
formAdd.addEventListener('reset', function (e) {
    city.innerHTML = `<option value="">--城市--</option>`
    area.innerHTML = `<option value="">--地区--</option>`
})

//初始化省市区
async function initcitySelect() {
    // 1 获取省份
    const provinceResult = await axios({ url: '/api/province' })
    // 2 渲染省下来列表
    province.innerHTML = provinceResult.data.reduce((a, b) => a + ` <option value="${b}">${b}</option>`, '<option value="">--省份--</option>')
    // 3 给省份组件 绑定 change => 获取对应城市列表
    province.addEventListener('change', async function (e) {
        const cityResult = await axios({ url: '/api/city', params: { pname: province.value } })
        city.innerHTML = cityResult.data.reduce((a, b) => a + ` <option value="${b}">${b}</option>`, '<option value="">--城市--</option>')
        //重置地区
        area.innerHTML = `<option value="">--地区--</option>`
    })
    // 4 给城市组件 绑定 change => 根据 省份 和 城市 去 获取对应 区域列表
    city.addEventListener('change', async function (e) {
        const areaResult = await axios({ url: '/api/area', params: { pname: province.value, cname: city.value } })
        area.innerHTML = areaResult.data.reduce((a, b) => a + ` <option value="${b}">${b}</option>`, '<option value="">--地区--</option>')
    })
}

//添加学员
formAdd.addEventListener('submit', async function (e) {
    e.preventDefault()
    const data = serialize(form, { hash: true, empty: true })
    const { id } = data
    delete data.id
    if (!/[a-zA-Z0-9\u4e00-\u9fa5]{1,30}/.test(data.name)) {
        toastTop('姓名请输入1-30位字符')
        return
    }
    if (!/[1-8]{1,1}/.test(data.group)) {
        toastTop('请输入组别为1-8的数字')
        return
    }
    //判断所有的输入框不能为空
    for (const key in data) {
        if (!data[key]) {
            toastTop('表单不能为空')
            return
        }
    }

    //字符串类型转换成数字类型
    data.age = +data.age
    data.gender = +data.gender
    data.salary = +data.salary
    data.hope_salary = +data.hope_salary
    data.group = +data.group
    if (document.querySelector('.modal-title').innerText === '添加学员') {
        //调用接口
        await axios({
            method: 'post',
            url: '/students',
            data
        })
    } else {
        await axios({
            method: 'put',
            url: `/students/${id}`,
            data
        })
    }

    modalBootstrap.hide()//隐藏模态框
    formAdd.reset()//重置表单
    toastTop('操作成功')//添加成功弹窗提示
    renderStudentList()//重新渲染学生列表
})

//删除功能
tbody.addEventListener('click', async function (e) {
    if (e.target.classList.contains('bi-trash')) {
        if (confirm('你确定要删除吗？')) {
            const { id } = e.target.dataset
            // console.log(index)
            const result = await axios({
                method: 'DELETE',
                url: `/students/${id}`,
            })
            console.log(result);
            toastTop('删除成功')//添加成功弹窗提示
            renderStudentList()//重新渲染学生列表
        }
    }
})

//编辑功能
tbody.addEventListener('click', async function (e) {
    if (e.target.classList.contains('bi-pen')) {
        const { id } = e.target.dataset
        modalBootstrap.show()
        document.querySelector('.modal-title').innerText = '编辑学员'

        const result = await axios({ url: `/students/${id}` })
        //回填单选框
        document.querySelector(`[name="gender"][value='${result.data.gender}']`).checked = true

        const names = document.querySelectorAll('[name]');
        // console.log(names);

        const cityResult = await axios({ url: '/api/city', params: { pname: result.data.province } })
        city.innerHTML = cityResult.data.reduce((a, b) => a + ` <option value="${b}">${b}</option>`, '<option value="">--城市--</option>')

        const areaResult = await axios({ url: '/api/area', params: { pname: result.data.province, cname: result.data.city } })
        area.innerHTML = areaResult.data.reduce((a, b) => a + ` <option value="${b}">${b}</option>`, '<option value="">--地区--</option>')

        //回填文本数据
        names.forEach(ele => {
            if (ele.name !== "gender") {
                ele.value = result.data[ele.name]
            }
        })
    }
})





